import React, { useState } from 'react';
import { Form, Input, Button, Card, Typography, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { AdminUser } from '../../types';
import { Storage, STORAGE_KEYS } from '../../utils/storage';
import { mockAdminUsers } from '../../services/mockData';

const { Title, Text } = Typography;

const AdminLogin: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const handleLogin = async (values: any) => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      const localUsers = Storage.get<AdminUser[]>(STORAGE_KEYS.ADMIN_USER + 'S') || [];
      const adminUser = localUsers.find(u => u.username === values.username) || mockAdminUsers.find(u => u.username === values.username);
      if (adminUser && (values.password === (adminUser.password || 'admin123'))) {
        Storage.set(STORAGE_KEYS.ADMIN_USER, adminUser);
        message.success('登录成功');
        navigate('/admin');
      } else {
        message.error('用户名或密码错误');
      }
    } catch (error) {
      message.error('登录失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ 
      minHeight: '100vh', 
      display: 'flex', 
      alignItems: 'center', 
      justifyContent: 'center',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
    }}>
      <Card style={{ width: 400, boxShadow: '0 8px 32px rgba(0,0,0,0.3)' }}>
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <Title level={2} style={{ color: '#1890ff' }}>商城管理系统</Title>
          <Text type="secondary">管理员登录</Text>
        </div>

        <Form onFinish={handleLogin} size="large">
          <Form.Item 
            name="username" 
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input 
              prefix={<UserOutlined />} 
              placeholder="管理员用户名" 
            />
          </Form.Item>
          
          <Form.Item 
            name="password" 
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password 
              prefix={<LockOutlined />} 
              placeholder="密码" 
            />
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              style={{ width: '100%' }} 
              loading={loading}
            >
              登录
            </Button>
          </Form.Item>
        </Form>

        <div style={{ textAlign: 'center', marginTop: 24 }}>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            测试账号：admin 密码：admin123
          </Text>
        </div>
      </Card>
    </div>
  );
};

export default AdminLogin;
